package adminorg;


import java.util.LinkedHashMap;


import com.vaadin.data.Item;
//import com.vaadin.data.util.filter.Compare.Equal;
//import com.vaadin.data.util.sqlcontainer.SQLContainer;
import com.vaadin.ui.Accordion;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.DefaultFieldFactory;
import com.vaadin.ui.Form;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.Label;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.MenuBar.Command;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Window.Notification;
import com.vaadin.ui.Panel;
import com.vaadin.ui.Table;
import com.vaadin.ui.TabSheet;
import com.vaadin.ui.TextField;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.themes.Runo;
import com.vaadin.ui.Field;
import com.vaadin.ui.Component;
import com.vaadin.data.Container;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.filter.Compare.Equal;
import com.vaadin.data.util.filter.Not;

import adminorg.DatabaseHelper;
import adminorg.confWindow;
//import adminorg.db.*;
import com.oros.db.*;
//import adminorg.db.AETableContainer;


public class DocumentForm extends Accordion{


	private static final long serialVersionUID = 7585826489324450967L;
	private Accordion docaccordion = null;
	private VerticalLayout CmainLayout = null;
	private VerticalLayout CDetailLayout = null;
	private HorizontalLayout CDhLayout2 = null;
	private HorizontalLayout ChLayout2 = null;
	private ComboBox CompCombo = null;
	private Panel Cpanel = null;
	private Panel CgridPanel = null;
	private Panel CDpanel = null;
	private Panel CDgridPanel = null;
	private VerticalLayout CvLayout2 = null;
	private HorizontalLayout ChLayout3 = null;
	private VerticalLayout CDvLayout2 = null;
	private HorizontalLayout CDhLayout3 = null;
	private HorizontalLayout MenuLayout = null;
	private Button bCancel = null;
	private Button bAply = null;
	private Button bDCancel = null;
	private Button bDAply = null;
	private Table DocGrid = null;
	private Table DocRightGrid = null;
	private MenuBar CmenuBar = null;
	private MenuBar CDmenuBar = null;
	private Object MainId = null,MainDocId=null;
	private Form DocForm = null;
	private Form DocRightForm = null;
	private MenuBar.MenuItem mAdd = null;
	private MenuBar.MenuItem mEdit = null;
	private MenuBar.MenuItem mDel = null;
	private MenuBar.MenuItem mdAdd = null;
	private MenuBar.MenuItem mdEdit = null;
	private MenuBar.MenuItem mdDel = null;
	private DatabaseHelper dbHelp = null;
    private boolean isNewDocumentAdded=false;
    private Object newEditDocumentId=null;
    private Object newEditDocRightId=null;
    private ComboBox docPostCombo;
    private ComboBox doctypeCombo;
    
    private Panel detachedPanel;
	private void enableCPanel()
    {
    	Cpanel.setVisible(true);
    	mEdit.setEnabled(false);
    	mDel.setEnabled(false);
    	mAdd.setEnabled(false);
		CDetailLayout.setVisible(false);
    }
	private void ensureDisableAllPanels()
	{
		if (CDpanel.isVisible())
		{
		  try {
			dbHelp.views.getDocRightViewContainer().rollback();
           } catch (Exception e) {
        	AEHelper.logException(e,"Doc right DCancel Button");
        	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
           }
		   DocRightForm.setItemDataSource(null);
		}
		if (Cpanel.isVisible())
		{
			
			try {
			    dbHelp.views.getDocumentViewContainer().rollback();
            } catch (Exception e) {
        	  AEHelper.logException(e,"Cancel button");
        	   docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
            }
		    DocForm.setItemDataSource(null);
		}	
		
		disableCPanel();
		disableCDPanel();
	}
    private void disableCPanel()
    {
    	Cpanel.setVisible(false);
    	if (DocGrid.getValue()==null){
    		mEdit.setEnabled(false);
    		mDel.setEnabled(false);
    		CDetailLayout.setVisible(false);
    	} else {
    		mEdit.setEnabled(true);
    		mDel.setEnabled(true);
    		CDetailLayout.setVisible(true);
    	}
    	mAdd.setEnabled(true);
    	newEditDocumentId=null;
    }
	private void enableCDPanel()
    {
    	CDpanel.setVisible(true);
   		mdEdit.setEnabled(false);
   		mdDel.setEnabled(false);
        mdAdd.setEnabled(false);    		
    }
	private void disableCDPanel()
    {
    	CDpanel.setVisible(false);
       	if (DocRightGrid.getValue()==null){
    		mdEdit.setEnabled(false);
    		mdDel.setEnabled(false);
    	} else {
    		mdEdit.setEnabled(true);
    		mdDel.setEnabled(true);
    	}
        mdAdd.setEnabled(true);    
        newEditDocRightId=null;
    }
	
	final private void updatePostCombo(Object id) throws Exception
	{
		if (isNewDocumentAdded)
		{
			docPostCombo.setVisible(true);
			Object postlast = docPostCombo.getValue();
			   if (postlast!=null)
			   {
				   dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(id,"documents.post", postlast);
		 	   }
			 //dbHelp.views.getDocPostViewContainer().showSourceDetailedInfo(AETableContainer.SHOW_INFO_ALL);
		}
		else
		docPostCombo.setVisible(false);
		Object typelast = doctypeCombo.getValue();
		String curtype = (String)dbHelp.views.getDocumentViewContainer().
				getContainerProperty(id, "documents.file_type").getValue();
		if (curtype!=null && curtype.length()>0)
		{
			if (typelast==null || !typelast.equals(curtype))
			{
				typelast = curtype;
				doctypeCombo.setValue(typelast);
			}
		}
		if (typelast!=null)
		{
			dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(id,"documents.file_type",typelast);
		}
	}
	private Command menuCommand = new Command() {
		private static final long serialVersionUID = 2164852925709550L;
		public void menuSelected(MenuItem selectedItem) {
			try {
        		dbHelp.views.getDocumentViewContainer().rollback();
            	if (dbHelp.views.getDocPostViewContainer().size()==0)
                    throw new Exception(dbHelp.getWords("PleaseFirstHaveYourPostEnteredInTheOrganizationChart"));
			} catch (Exception e) {
            	AEHelper.logException(e,"Doc rollback");
            	docaccordion.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
            	return;
            }
			final Object ID = DocGrid.getValue();
            if (selectedItem.getText().equals(dbHelp.getWords("New"))){
            	Cpanel.setCaption(dbHelp.getWords("AddingDocument"));
            	isNewDocumentAdded=true;
            	try
            	{
            	  Object tempItemId = dbHelp.views.getDocumentViewContainer().addItem(null,new String[]{"docrights.right"},new Object[]{DocumentView.DOC_RIGHT_CREATOR});
            	  if (tempItemId==null) 
            	  {
	                	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerOverloaded"), Notification.TYPE_ERROR_MESSAGE);
	                	disableCPanel();
            	  }
            	  else
            	  {
            		  newEditDocumentId = tempItemId;
                  	  updatePostCombo(newEditDocumentId);
                	  enableCPanel();
            		  dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(newEditDocumentId, "docrights.right", DocumentView.DOC_RIGHT_CREATOR);
            	      DocForm.setItemDataSource(dbHelp.views.getDocumentViewContainer().getItem(tempItemId));
            	  }
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"New comp");
                	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), Notification.TYPE_ERROR_MESSAGE);
                	disableCPanel();
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Edit"))) {
            	isNewDocumentAdded = false;
				try
				{
					
				  int ids =((Integer) dbHelp.views.getDocumentViewContainer().
						getContainerProperty(ID,"docrights.right").getValue()).intValue();
				  if (ids!=DocumentView.DOCUMENT_RIGHT_CREATOR && ids!=DocumentView.DOCUMENT_RIGHT_WRITER)
				  {
	                	docaccordion.getWindow().showNotification(dbHelp.getWords("OnlyCreatorsAndWritersCanEditThisDocument"), Notification.TYPE_ERROR_MESSAGE);
	                	return;
				  }
				}
				catch(Exception e)
				{
                	AEHelper.logException(e,"Doc check right");
                	docaccordion.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
                	return;
				}
            	Cpanel.setCaption(dbHelp.getWords("EditingDocumentInfo"));
    			if (ID==null)
    			{
                	docaccordion.getWindow().showNotification(dbHelp.getWords("NoDocumentIsChosen"), Notification.TYPE_ERROR_MESSAGE);
                	disableCPanel();
                	return;
    			}

            	try
            	{
            		newEditDocumentId=ID;
                	updatePostCombo(ID);
                	enableCPanel();
            	  DocForm.setItemDataSource(dbHelp.views.getDocumentViewContainer().getItem(ID));
            	}
            	catch(Exception e)
            	{
            		disableCPanel();
            		AEHelper.logException(e,"Doc edit");
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Delete"))){
    			if (ID==null)
    			{
                	docaccordion.getWindow().showNotification(dbHelp.getWords("NoDocumentIsChosen"), Notification.TYPE_ERROR_MESSAGE);
                	return;
    			}
				try
				{
					
				  int ids =((Integer) dbHelp.views.getDocumentViewContainer().
						getContainerProperty(ID,"docrights.right").getValue()).intValue();
				  if (ids!=DocumentView.DOCUMENT_RIGHT_CREATOR)
				  {
	                	docaccordion.getWindow().showNotification(dbHelp.getWords("OnlyCreatorsCanDeleteThisDocument"), Notification.TYPE_ERROR_MESSAGE);
	                	return;
				  }
				}
				catch(Exception e)
				{
                	AEHelper.logException(e,"Doc check right");
                	docaccordion.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
                	return;
				}
                DocGrid.select(null);
            	docaccordion.getWindow().addWindow(new confWindow(dbHelp.getWords("RecordDeleting"),
            			dbHelp.getWords("DocumentWillBeRemoved"),
            			new confWindow.Callback() {
							
							private static final long serialVersionUID = 5053817083273511190L;

							@Override
							public void onDialogResult(boolean resultIsYes) {
								
								if (resultIsYes){
	
									try {
										AERawItem item =(AERawItem) dbHelp.views.getDocumentViewContainer().getItem(ID);
										if (item!=null)
										{
											String resourceId =(String)item.getColumnValue(DocumentView.columnDocumentsView_Link);
										    dbHelp.views.getDocumentViewContainer().removeItem(ID,1);
										    dbHelp.views.getDocumentViewContainer().commit();
										    dbHelp.views.docservice.removeDocument(resourceId, false);
										    dbHelp.views.getDocumentViewContainer().refresh();
										}
					                } catch (Exception e) {
					                	AEHelper.logException(e,"Doc removal");
					                	docaccordion.getWindow().showNotification(e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					                }
								}
								else DocGrid.select(ID);		
							}
						}
            		));
            };
        }
    };
    
    private Command menuDCommand = new Command() {
		private static final long serialVersionUID = 1309726789652195092L;

		public void menuSelected(MenuItem selectedItem) {
			if (MainDocId==null)
			{
            	docaccordion.getWindow().showNotification(dbHelp.getWords("NoDocumentIsChosen"), Notification.TYPE_ERROR_MESSAGE);
            	return;
			}
        	try {
        		dbHelp.views.getDocRightViewContainer().rollback();
            } catch (Exception e) {
            	AEHelper.logException(e,"DocRight rollback");
            }

			if (selectedItem.getText().equals(dbHelp.getWords("New"))){
            	CDpanel.setCaption(dbHelp.getWords("AssigningRights"));
            	enableCDPanel();
            	try
            	{
            	   Object tempItemId = dbHelp.views.getDocRightViewContainer().addItem(null,
            			   new String[]{"docrights.docid"},new Object[]{MainDocId});
            	   if (tempItemId==null)
            	   {
	                	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerOverloaded"), Notification.TYPE_ERROR_MESSAGE);
	                	disableCDPanel();
	                	return;
            	   }
            	   newEditDocRightId=tempItemId;
            	   
            	   DocRightForm.setItemDataSource(dbHelp.views.getDocRightViewContainer().getItem(tempItemId));
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"New DocRight");
                	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), Notification.TYPE_ERROR_MESSAGE);
                	disableCDPanel();
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Edit"))) {
            	Object tempId=DocRightGrid.getValue();
            	if (tempId==null)
            	{
                	docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseFirstSpecifyTheRowToEdit"), Notification.TYPE_ERROR_MESSAGE);
                	return;
            	}
            	newEditDocRightId=tempId;
            	CDpanel.setCaption(dbHelp.getWords("EditingRights"));
            	enableCDPanel();
            	try 
            	{
            	  DocRightForm.setItemDataSource(dbHelp.views.getDocRightViewContainer().getItem(tempId));
            	}
            	catch(Exception e)
            	{
            		AEHelper.logException(e,"DocRight Edit:");
            	}
            }else if (selectedItem.getText().equals(dbHelp.getWords("Delete"))){
            	final Object ID=DocRightGrid.getValue();
            	if (ID==null)
            	{
                	docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseFirstSpecifyTheRowToEdit"), Notification.TYPE_ERROR_MESSAGE);
                	return;
            	}
            	DocRightGrid.select(null);     
            	docaccordion.getWindow().addWindow(new confWindow(dbHelp.getWords("RecordDeleting"),
            			dbHelp.getWords("DeletingRightsForDocument"),
            			new confWindow.Callback() {
							
							/**
							 * 
							 */
							private static final long serialVersionUID = 5952451279354615886L;

							@Override
							public void onDialogResult(boolean resultIsYes) {
								
								if (resultIsYes){
					                try {
										dbHelp.views.getDocRightViewContainer().removeItem(ID);
					                	dbHelp.views.getDocRightViewContainer().commit();
					                	dbHelp.views.checkDocumentRights(MainDocId);
					                	dbHelp.views.getDocRightViewContainer().refresh();
										
					                } catch (Exception e) {
					                	AEHelper.logException(e,"DocRight Item removal");
					                	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
					                }
								}
								else DocRightGrid.select(ID);
							}
						}
            		));
            };
        }
    };
	public Integer getCurrentDocSelection()
	{
		Object docid = DocGrid.getValue();
		if (docid==null) return null;
		try 
		{ Integer did;
		 if (docid instanceof Integer) did= (Integer)docid;
		 else did= new Integer(Integer.parseInt(docid.toString()));
		 return (Integer)dbHelp.views.getDocumentViewContainer().getIdAtLevel(did, 1);
		} catch(Exception e)
		{
			
		}
		return null;
	}
	public DocumentForm(DatabaseHelper dbHelper) throws Exception {
		
		this.dbHelp = dbHelper;
		docaccordion = new Accordion();
		docaccordion.setImmediate(false);
		//docaccordion.setSizeFull();
		
		CmainLayout = new VerticalLayout();
		CmainLayout.setImmediate(false);
		CmainLayout.setMargin(false);
		CmainLayout.setSpacing(true);
		CompCombo = DefaultWindow.getCompanyComboBox(dbHelp,docaccordion,new DefaultWindow.newCompanyEvent() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = 8971633017519602430L;

			@Override
			public void notifyOfNewCompany(Integer id) {
				 disableCPanel();
            	 disableCDPanel();
			}
		});
		CmenuBar = new MenuBar();
		CmenuBar.setImmediate(false);
		mAdd = CmenuBar.addItem(dbHelp.getWords("New"), menuCommand);
		mEdit = CmenuBar.addItem(dbHelp.getWords("Edit"), menuCommand);
		mEdit.setEnabled(false);
		mDel = CmenuBar.addItem(dbHelp.getWords("Delete"), menuCommand);
		mDel.setEnabled(false);
		MenuLayout = new HorizontalLayout();
		MenuLayout.setImmediate(true);
		MenuLayout.addComponent(CmenuBar);
		MenuLayout.addComponent(CompCombo);
		MenuLayout.setWidth("100%");
		MenuLayout.setComponentAlignment(CompCombo, Alignment.TOP_RIGHT);
		
		
		CmainLayout.addComponent(MenuLayout);
		
		ChLayout2 = new HorizontalLayout();
		ChLayout2.setImmediate(false);

		ChLayout2.setMargin(false);
		//ChLayout2.setSizeFull();
		ChLayout2.setSpacing(true);	
		// CompGrid
		    String[] docGridColumns = new String[]{"documents.name_doc","documents.description","right_title","orgschema.post_name","doctype_name","documents.link"};
			Container docContainer = new AESubContainer(
					dbHelp.views.getDocumentViewContainer(),true,docGridColumns);
			
			DocGrid = new Table(null,docContainer);
		    DocGrid.setImmediate(true);
		    DocGrid.setContainerDataSource(docContainer);
		    //DocGrid.addContainerProperty("name_with_link",Label.class,null);
		    DocGrid.addGeneratedColumn("documents.name_doc", new Table.ColumnGenerator() {
				
				private static final long serialVersionUID = 1L;

				@Override
				public Object generateCell(Table source, Object itemId, Object columnId) {
					try {
						
					AERawItem item =(AERawItem) dbHelp.views.getDocumentViewContainer().getItem(itemId);
					String resourceId =(String) item.getColumnValue(DocumentView.columnDocumentsView_Link);
					String type = (String) item.getColumnValue(DocumentView.columnDocumentsView_Type);
					String title = (String) item.getColumnValue(DocumentView.columnDocumentsView_Name);
					Integer right=(Integer)item.getColumnValue(DocumentView.columnDocumentsView_Right);
					boolean isEdit = right!=null && right.intValue()<3;
					String labelData=DocumentServe.getDocumentLink(resourceId, type, title, isEdit);
					return new Label(labelData,Label.CONTENT_XHTML);
					}
					catch(Exception e)
					{
						return new Label("Error: "+e);
					}
				}
			});
		    DocGrid.setVisibleColumns(docGridColumns);		
		    DocGrid.setColumnHeaders(dbHelp.getTranslatedStrings(new String[]{"DocTitle","Description","Rights","Post","FileType","Link"}));	
		    DocGrid.setColumnCollapsingAllowed(true);
		    DocGrid.setColumnReorderingAllowed(true);
		    DocGrid.setSelectable(true);
		    //DocGrid.setSizeFull();
		    DocGrid.setStyleName(Runo.TABLE_SMALL);
		    DocGrid.setWidth("650px");
		    ChLayout2.addComponent(DocGrid);
		Cpanel = new Panel();
		Cpanel.setCaption(dbHelp.getWords("AddingDocument"));
		Cpanel.setVisible(false);
		Cpanel.setImmediate(false);
		
		CvLayout2 = new VerticalLayout();
		CvLayout2.setImmediate(false);
		CvLayout2.setMargin(true);
		doctypeCombo=new ComboBox(dbHelp.getWords("Type"));
		LinkedHashMap<String,String> doctype = dbHelp.views.getDocumentTypesMap();
		for(String tp:doctype.keySet())
		{
		    doctypeCombo.addItem(tp);
		    doctypeCombo.setItemCaption(tp, doctype.get(tp));
		}
		doctypeCombo.setNewItemsAllowed(false);
		doctypeCombo.setNullSelectionAllowed(false);
		doctypeCombo.setRequired(true);
		doctypeCombo.setVisible(true);
		doctypeCombo.setWidth("243px");
		docPostCombo = new ComboBox(dbHelp.getWords("Post"));
		docPostCombo.setImmediate(true);
		docPostCombo.setNullSelectionAllowed(false);
		docPostCombo.setContainerDataSource(dbHelp.views.getDocPostViewContainer());
		docPostCombo.setItemCaptionPropertyId("orgschema.post_name");
		docPostCombo.select(dbHelp.views.getDocPostViewContainer().firstItemId());
		docPostCombo.setNewItemsAllowed(false);
		docPostCombo.setRequired(true);
		docPostCombo.setWidth("243px");
		
		DocForm = new Form();
		DocForm.setFormFieldFactory(new DefaultFieldFactory(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 7359753568658330130L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
				AERawItem aeitem = (AERawItem)item;
				if (aeitem.isNew())
				{
				   if (propertyId.equals("documents.file_type")){ 
					   return doctypeCombo;
				   }
                   if (propertyId.equals("documents.post")){
                       return docPostCombo;
                   }
				}
				boolean isDocumentName=propertyId.equals("documents.name_doc");
				boolean isDocumentDescription=propertyId.equals("documents.description");
				if (!isDocumentName && !isDocumentDescription) return null;
				Field field = super.createField(item, propertyId, uiContext);
				field.setRequired(false);
				field.setVisible(true);
				field.setWidth("243px");
                if (isDocumentName){
					field.setRequired(true);
                	field.setCaption(dbHelp.getWords("DocTitle"));
                }
                if (isDocumentDescription){
					field.setRequired(true);
                	field.setCaption(dbHelp.getWords("Description"));
                }
				if (field instanceof TextField) {
                    ((TextField) field).setNullRepresentation("");
                }
				
				return field;

			}
		});

		ChLayout3 = new HorizontalLayout();
		ChLayout3.setImmediate(true);
		
		// bAply
		bAply = new Button();
		bAply.setCaption(dbHelp.getWords("Apply"));
		bAply.setImmediate(true);
		bAply.setTabIndex(5);
		ChLayout3.addComponent(bAply);
		
		// bCancel
		bCancel = new Button();
		bCancel.setCaption(dbHelp.getWords("Cancel"));
		bCancel.setImmediate(true);
		ChLayout3.addComponent(bCancel);

		DocForm.setFooter(ChLayout3);		
		CvLayout2.addComponent(DocForm);		
		Cpanel.setContent(CvLayout2);
		ChLayout2.addComponent(Cpanel);
		//ChLayout2.setExpandRatio(DocGrid, 1.0f);
		ChLayout2.setSizeUndefined();
		CgridPanel = new Panel();
		CgridPanel.setContent(ChLayout2);
		CgridPanel.setScrollable(true);
		CmainLayout.addComponent(CgridPanel);
		//CmainLayout.addComponent(ChLayout2);
		detachedPanel = new Panel();
		docaccordion.addTab(detachedPanel, dbHelp.getWords("Documents"));
		detachedPanel.addComponent(CmainLayout);
		//DETAIL
		CDetailLayout = new VerticalLayout();
		CDetailLayout.setImmediate(true);
		CDetailLayout.setMargin(false);
		CDetailLayout.setSpacing(false);
		CDetailLayout.setWidth("100%");
		
		CDmenuBar = new MenuBar();
		CDmenuBar.setImmediate(false);
		mdAdd = CDmenuBar.addItem(dbHelp.getWords("New"), menuDCommand);
		mdEdit = CDmenuBar.addItem(dbHelp.getWords("Edit"), menuDCommand);
		mdEdit.setEnabled(false);
		mdDel = CDmenuBar.addItem(dbHelp.getWords("Delete"), menuDCommand);
		mdDel.setEnabled(false);
		CDetailLayout.addComponent(CDmenuBar);
		
		CDhLayout2 = new HorizontalLayout();
		CDhLayout2.setImmediate(false);

		CDhLayout2.setMargin(false);
		CDhLayout2.setHeight("100%");
		CDhLayout2.setSpacing(true);	
		DocRightGrid = new Table(null);
		DocRightGrid.setWidth("300px");
		DocRightGrid.setImmediate(true);
		String[] docRightGridColumns = new String[]{"orgschema.post_name","right_title"};
		Container docRightGridContainer=new AESubContainer(dbHelp.views.getDocRightViewContainer(),
				     true,docRightGridColumns);
		DocRightGrid.setContainerDataSource(docRightGridContainer);
	    DocRightGrid.setVisibleColumns(docRightGridColumns);		
		DocRightGrid.setColumnHeaders(dbHelp.getTranslatedStrings(new String[]{"Post","Rights"}));
		
		  DocRightGrid.setColumnCollapsingAllowed(true);
		  DocRightGrid.setColumnReorderingAllowed(true);
		  DocRightGrid.setSelectable(true);
		//DocRightGrid.setSizeFull();
		  DocRightGrid.setStyleName(Runo.TABLE_SMALL);
		  DocRightGrid.setHeight("100%");

		refreshDetailGrid();
		CDhLayout2.addComponent(DocRightGrid);
		
		CDpanel = new Panel();
		CDpanel.setCaption(dbHelp.getWords("AssigningRights"));
		CDpanel.setVisible(false);
		CDpanel.setImmediate(true);
		
		CDvLayout2 = new VerticalLayout();
		CDvLayout2.setImmediate(false);
		CDvLayout2.setMargin(true);
		DocRightForm = new Form();
		final ComboBox rightCombo=new ComboBox(dbHelp.getWords("Rights"));
		rightCombo.addItem(DocumentView.DOC_RIGHT_CREATOR);
		rightCombo.addItem(DocumentView.DOC_RIGHT_WRITER);
		rightCombo.addItem(DocumentView.DOC_RIGHT_READER);
		rightCombo.setItemCaption(DocumentView.DOC_RIGHT_CREATOR, dbHelp.getWords("Creator"));
		rightCombo.setItemCaption(DocumentView.DOC_RIGHT_WRITER, dbHelp.getWords("Writer"));
		rightCombo.setItemCaption(DocumentView.DOC_RIGHT_READER, dbHelp.getWords("Reader"));
		rightCombo.setNewItemsAllowed(false);
		rightCombo.setNullSelectionAllowed(false);
		rightCombo.setVisible(true);
		rightCombo.setWidth("243px");
		final ComboBox docrightPostCombo= new ComboBox(dbHelp.getWords("Post"));
		docrightPostCombo.setImmediate(true);
		docrightPostCombo.setNullSelectionAllowed(false);
		docrightPostCombo.setContainerDataSource(dbHelp.getOrgschemaReadContainer());
		docrightPostCombo.setItemCaptionPropertyId("post_name");
		docrightPostCombo.select(dbHelp.getOrgschemaReadContainer().firstItemId());
		docrightPostCombo.setNewItemsAllowed(false);
		docrightPostCombo.setNullSelectionAllowed(false);
		docrightPostCombo.setVisible(true);
		docrightPostCombo.setWidth("243px");
		
		DocRightForm.setFormFieldFactory(new DefaultFieldFactory(){
			/**
			 * 
			 */
			private static final long serialVersionUID = 853275780771407L;

			@Override
			public Field createField(Item item, Object propertyId,
                    Component uiContext) {
				if (propertyId.equals("docrights.right"))
			    {
					return rightCombo;
			    }
                if (propertyId.equals("docrights.post"))
                {
                    return docrightPostCombo;	
                }
                return null;
                /*******************
				Field field = super.createField(item, propertyId, uiContext);
				field.setWidth("243px");
				field.setRequired(false);
				field.setVisible(false);
				return field;
				*******************/

			}
		});
		CDhLayout3 = new HorizontalLayout();
		CDhLayout3.setImmediate(false);
		
		// bAply
		bDAply = new Button();
		bDAply.setCaption(dbHelp.getWords("Apply"));
		bDAply.setImmediate(true);
		bDAply.setTabIndex(5);
		CDhLayout3.addComponent(bDAply);
		
		// bCancel
		bDCancel = new Button();
		bDCancel.setCaption(dbHelp.getWords("Cancel"));
		bDCancel.setImmediate(true);
		CDhLayout3.addComponent(bDCancel);
		//addButtonListeners();
		DocRightForm.setFooter(CDhLayout3);		
		CDvLayout2.addComponent(DocRightForm);
		CDpanel.setContent(CDvLayout2);
		CDhLayout2.addComponent(CDpanel);
		CDgridPanel = new Panel();
		CDgridPanel.setContent(CDhLayout2);
		CDgridPanel.setScrollable(true);
		CDetailLayout.addComponent(CDgridPanel);
		CDetailLayout.setVisible(false);
		docaccordion.addTab(CDetailLayout,dbHelp.getWords("AssignedRights"));
		docaccordion.addListener(new TabSheet.SelectedTabChangeListener() {
			
			private static final long serialVersionUID = 1L;

			@Override
			public void selectedTabChange(SelectedTabChangeEvent event) {
				
				int pos = docaccordion.getTabPosition(docaccordion.getTab(docaccordion.getSelectedTab()));
				String pagename=null;
				switch(pos)
				{
				case 0:
					pagename="documents";
					break;
				case 1:
					pagename=MainId==null || MainId.equals(new Integer(0))?"documents":"documents."+MainId;
					break;
				}
				if (pagename!=null) try
						{
					       dbHelp.getCurrentUserTrackItem().getItemProperty("last_page").setValue(pagename);
					       dbHelp.saveCurrentUserTrackInfo();
						}
				       catch(Exception e)
				       {
				    	   e.printStackTrace();
				       }		
			}
		});
		addButtonListeners();
		addGridListeners();
	}
	
	private void addGridListeners(){
		DocGrid.addListener(new Property.ValueChangeListener() {
			
			private static final long serialVersionUID = 3520836255628012161L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property property = event.getProperty();
		        if (property == DocGrid) {
		            Item item = DocGrid.getItem(DocGrid.getValue());
		            if (item != DocForm.getItemDataSource()) {
		            	disableCPanel();
		            	refreshDetailGrid();
		            }
		        }
				
			}
		} );
 
		DocRightGrid.addListener(new Property.ValueChangeListener() {
			
			private static final long serialVersionUID = -4262942439248536230L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				Property property = event.getProperty();
		        if (property == DocRightGrid) {
		            Item item = DocRightGrid.getItem(DocRightGrid.getValue());
		            if (item != DocRightForm.getItemDataSource()) {
		            	disableCDPanel();
		            }
		        }
				
			}
		} );
	}	
	private void addButtonListeners(){
		dbHelp.addCompanyListener(new Property.ValueChangeListener() {
			
			private static final long serialVersionUID = -5391925332171622219L;

			@Override
			public void valueChange(ValueChangeEvent event) {
                 Object id = CompCombo.getValue();	
                 if (id!=null && !(id instanceof Integer))
                 {
                	 id = Integer.parseInt(id.toString());
                 }
                 if (id==null || !id.equals(dbHelp.getCompanyId()))
                 {
                	 CompCombo.setValue(dbHelp.getCompanyId());
                	
                 }
			}
		});
		bAply.addListener(new Button.ClickListener() {			
			private static final long serialVersionUID = -3143253462555220935L;

			@Override
			public void buttonClick(ClickEvent event) {
				DocForm.commit();
				if (!DocForm.isValid()) {
	                return;
	            }
				try {
				    if (isNewDocumentAdded)
				    {
				    	if (newEditDocumentId==null)
				    	{
				    		throw new Exception("DocForm result is null");
				    	}
				    	Property prop=dbHelp.views.getDocumentViewContainer().getContainerProperty(newEditDocumentId,"documents.post");
				    	if (prop==null)
				    	{
				    		throw new Exception("DocForm properties are not set properly");
				    	}
				    	Object dat = prop.getValue();
				    	if (dat==null || !(dat instanceof Integer) || ((Integer)dat).intValue()<=0)
				    	{
				    		docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseSpecifyThePost"), "", Notification.TYPE_ERROR_MESSAGE);
				    		return;
				    	}
				    	dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(newEditDocumentId, "docrights.post", dat);
				    	String doctp =(String)dbHelp.views.getDocumentViewContainer().getContainerProperty(newEditDocumentId,"documents.file_type").getValue();
				    	if (doctp==null || doctp.length()==0)
				    	{
				    		docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseSpecifyTheDocumentType"), "", Notification.TYPE_ERROR_MESSAGE);
				    		return;
				    	}
				    	String doctit =(String)dbHelp.views.getDocumentViewContainer().getContainerProperty(newEditDocumentId,"documents.name_doc").getValue();
				    	if (doctit==null || doctit.trim().length()==0)
				    	{
				    		docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseSpecifyTheDocumentTitle"), "", Notification.TYPE_ERROR_MESSAGE);
				    		return;
				    	}
				    	String doclnk = dbHelp.views.docservice.getNewlyCreatedDocument(doctp, doctit);
				    	dbHelp.views.getDocumentViewContainer().setPropertiesOfItem(newEditDocumentId, "documents.link", doclnk);
				    	
				    }
				    //dbHelp.views.getDocumentViewContainer().showSourceDetailedInfo(AETableContainer.SHOW_INFO_ALL);
		            dbHelp.views.getDocumentViewContainer().commit();
		        } catch (Exception e) {
		        	try {dbHelp.views.getDocumentViewContainer().rollback();} catch(Exception e1){}
		        	AEHelper.logException(e,"Apply button click");
		        	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        }
				disableCPanel();
				
			}
		});
		bCancel.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -6839497274631461435L;

			@Override
			public void buttonClick(ClickEvent event) {
				ensureDisableAllPanels();
			}
		});
		bDAply.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -8375927111394468178L;

			@Override
			public void buttonClick(ClickEvent event) {
				if (newEditDocRightId==null)
				{
		        	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), "-", Notification.TYPE_ERROR_MESSAGE);
					disableCDPanel();
					return;
				}
				DocRightForm.commit();
				if (!DocRightForm.isValid()) {
	                return;
	            }
				try {
					Object lpost=dbHelp.views.getDocRightViewContainer().getContainerProperty(newEditDocRightId, "docrights.post").getValue();
					Object lright=dbHelp.views.getDocRightViewContainer().getContainerProperty(newEditDocRightId, "docrights.right").getValue();
					if (lpost==null || !(lpost instanceof Integer) || ((Integer)lpost).intValue()<=0)
					{
			        	docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseSpecifyThePostToAssignRights"), "", Notification.TYPE_ERROR_MESSAGE);
                        return;						
					}
					if (lright==null || !(lright instanceof Integer) || ((Integer)lright).intValue()<=0)
					{
			        	docaccordion.getWindow().showNotification(dbHelp.getWords("PleaseSpecifyTheRightToBeAssigned"), "", Notification.TYPE_ERROR_MESSAGE);
                        return;						
					}
					//dbHelp.views.getDocRightViewContainer().showSourceDetailedInfo(AETableContainer.SHOW_INFO_ALL);
				    dbHelp.views.getDocRightViewContainer().commit();
				    dbHelp.views.checkDocumentRights(MainDocId);
		        }
				catch(AEUniqueIndexViolationException e1)
				{
		        	docaccordion.getWindow().showNotification(dbHelp.getWords("ThisPostIsAlreadyAssignedWithRightsForThisDocument"), "", Notification.TYPE_ERROR_MESSAGE);
		        	try { dbHelp.views.getDocRightViewContainer().rollback();} catch(Exception e2){}
				}
				catch (Exception e) {
		        	AEHelper.logException(e,"Doc right Ok button click");
		        	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
		        	try { dbHelp.views.getDocRightViewContainer().rollback();} catch(Exception e2){}
		        }
				disableCDPanel();
				
			}
		});
		bDCancel.addListener(new Button.ClickListener() {			
			/**
			 * 
			 */
			private static final long serialVersionUID = -4491778313902174492L;

			@Override
			public void buttonClick(ClickEvent event) {
				ensureDisableAllPanels();
			}
		});
	}
	public void setDocRightEntry(String docno)
	{
		Integer docnr = new Integer(Integer.parseInt(docno));
		DocGrid.setValue(docnr);
		refreshDetailGrid();
		if (MainDocId!=null)
		{
			docaccordion.setSelectedTab(CDetailLayout);
		}
	}
	public void refreshDetailGrid(){
        MainDocId=null;
		if (DocGrid.getValue()==null) {
    		MainId = 0;
    	} else {
    		MainId =Integer.parseInt(DocGrid.getValue().toString());
    	}
		if (MainId.equals(0))
		{
			 DocRightGrid.setVisible(false);
             return;			
		}
		try
		{
			Object right=dbHelp.views.getDocumentViewContainer().getContainerProperty(MainId,"docrights.right").getValue();
			if (right==null || !right.equals(DocumentView.DOC_RIGHT_CREATOR))
			{
				 DocRightGrid.setVisible(false);
	             return;			
			}
			MainDocId = dbHelp.views.getDocumentViewContainer().getIdAtLevel(MainId, 1);
			dbHelp.views.getDocRightViewContainer().cleanAndAddContainerFilter(new Equal("docrights.docid",MainDocId));
			Object postval=dbHelp.views.getDocumentViewContainer().getContainerProperty(MainId, "documents.post").getValue();
			dbHelp.views.getDocRightViewContainer().addContainerFilter(new Not(new Equal("docrights.post",postval)));
		}
		catch(Exception e)
		{
			MainId=0;
		    DocRightGrid.setVisible(false);
			AEHelper.logException(e,"refresh detailed grid");
        	docaccordion.getWindow().showNotification(dbHelp.getWords("ServerError"), e.getMessage(), Notification.TYPE_ERROR_MESSAGE);
			return;
		}
		DocRightGrid.setVisible(true);	
		disableCDPanel();
		  
	}
	public Component detachMainLayout()
	{
		CompCombo.setVisible(false);
		detachedPanel.removeAllComponents();
		
		return CmainLayout;
	}
	public void reattachMainLayout()
	{
		ensureDisableAllPanels();
		detachedPanel.addComponent(CmainLayout);
		CompCombo.setVisible(true);
	}
	public Accordion getDocumentForm(){
		return docaccordion;
	}

}
